# CMake 环境要求
cmake_minimum_required(VERSION 3.16.1)

# 指定project名称和版本
project(cmake_test LANGUAGES C ASM)
message(NOTICE "start to build ${PROJECT_NAME}")

# 定义路径
set(BINARY_OUTPUT_DIR ${PROJECT_SOURCE_DIR}/output)
set(LIBRARY_OUTPUT_DIR ${PROJECT_SOURCE_DIR}/output)
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/output)

# 为指定目录或者文件定制编译选项，必须放在add_executable之前
# set_property(
#     SOURCE /home/huawei/project/cmake-test-project/source/src/sub/sub.c
#     APPEND
#     PROPERTY COMPILE_OPTIONS "-DDEBUG"
# )
# set_source_files_properties(${CMAKE_SOURCE_DIR}/src/sub/sub.c PROPERTIES COMPILE_OPTIONS "-O2")

##### 指定输出结果 #####
set(CMAKE_NM nm)
set(CMAKE_OBJDUMP objdump)

set(bin_file ${PROJECT_NAME}.elf)
set(map_file ${PROJECT_NAME}.map)
set(asm_file ${PROJECT_NAME}.asm)
set(sym_file ${PROJECT_NAME}.symbol)

add_executable(${bin_file})

# 添加子目录代码，里面通过target_sources接口添加需要编译的文件
add_subdirectory(src)

target_include_directories(${bin_file}
    PRIVATE
        ${PROJECT_SOURCE_DIR}/src/add
        ${PROJECT_SOURCE_DIR}/src/sub
)

target_compile_options(${bin_file}
    PRIVATE
    -O0 -Wall -Wextra -Werror)

target_link_options(${bin_file}
    PRIVATE
        -t # 打印链接文件名
        -Wl,-Map=${EXECUTABLE_OUTPUT_PATH}/${map_file}) # 输出MAP文件

# target_link_options(${bin_file}
#     PRIVATE
#         -nostdlib # 不自动链接gcc自带的lib，比如标准C库，启动文件等
#         -Wl,-Bstatic # 不链接共享库
#         -t # 打印链接文件名
#         -Wl,--no-check-sections # 不检查段空间合法性
#         -Wl,-Map=${EXECUTABLE_OUTPUT_PATH}/${map_file}) # 输出MAP文件
#         -T${PROJECT_SOURCE_DIR}/config/lds/${PROJECT_NAME}.lds)

# 通过输出结果生成其它文件
add_custom_command(
    TARGET ${bin_file} POST_BUILD
    COMMAND ${CMAKE_NM} -s -S -n ${EXECUTABLE_OUTPUT_PATH}/${bin_file} > ${EXECUTABLE_OUTPUT_PATH}/${sym_file} # 生成symbol文件
    COMMAND ${CMAKE_OBJDUMP} -d -a ${EXECUTABLE_OUTPUT_PATH}/${bin_file} > ${EXECUTABLE_OUTPUT_PATH}/${asm_file} # 生成ASM文件
    VERBATIM
)

# 输出各个section
# include(${PROJECT_SOURCE_DIR}/config/project/${PROJECT_NAME}.cmake)
# foreach(section_name ${OUTPUT_SECTIONS_LIST})
#     add_custom_command(
#         TARGET ${bin_file} POST_BUILD
#         COMMAND ${CMAKE_OBJCOPY} -O binary -j ${section_name} ${EXECUTABLE_OUTPUT_PATH}/${bin_file} ${EXECUTABLE_OUTPUT_PATH}/${section_name}
#         VERBATIM
#     )
# endforeach()